package cn.zysuyuan.item.service.impl;

import cn.zysuyuan.common.entity.Constant;
import cn.zysuyuan.common.entity.PageResult;
import cn.zysuyuan.common.utils.UUIDUtil;
import cn.zysuyuan.item.entity.MedicinalProductBase;
import cn.zysuyuan.item.mapper.MedicinalProductBaseMapper;
import cn.zysuyuan.item.service.MedicinalProductBaseService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author flypig
 * @version 1.0
 * @date 2019/10/30 2:42
 */
@Service
public class MedicinalProductBaseServiceImpl implements MedicinalProductBaseService {

    @Autowired
    private MedicinalProductBaseMapper medicinalProductBaseMapper;


    @Override
    public PageResult<MedicinalProductBase> selectList(Map<String, Object> map) {

        System.out.println("药品id：" + map.get("id"));
        /**
         * 将省市区组成地址
         */
        String bProvinceSeek = (String) map.get("bProvinceSeek");
        String bCitySeek = (String)map.get("bCitySeek");
        String bRegionSeek = (String)map.get("bRegionSeek");
        String bPosition = "";
        if(bProvinceSeek !=null && !"".equals(bProvinceSeek)){
            bPosition =bProvinceSeek;
        }
        if(bCitySeek !=null && !"".equals(bCitySeek)){
            bPosition =bPosition+"|"+bCitySeek;
        }
        if(bRegionSeek !=null && !"".equals(bRegionSeek)){
            bPosition =bPosition+"|"+bRegionSeek;
        }

        map.put("bPosition", bPosition);

        List<MedicinalProductBase> listTBH= this.medicinalProductBaseMapper.selectList(map);   //获取表格数据信息

        /**
         * 将查询到的地址拆成省市区
         */
        if(listTBH != null && listTBH.size()>0){
            for(int i=0;i<listTBH.size();i++){
                String[] positions=listTBH.get(i).getbPosition().split("\\|");
                if(positions != null && positions.length>0){

                    for (int x=0;x<positions.length;x++){

                        switch(x){
                            case 0:
                                listTBH.get(i).setbProvince(positions[x]);
                                break;
                            case 1:
                                listTBH.get(i).setbCity(positions[x]);
                                break;
                            case 2:
                                listTBH.get(i).setbRegion(positions[x]);
                                break;
                        }
                    }
                }
                /**将|替换成空格*/
                listTBH.get(i).setbPosition(listTBH.get(i).getbPosition().replace("|", "  "));
            }
        }

        return new PageResult<MedicinalProductBase>(listTBH);
    }

    @Override
    public int insert(MedicinalProductBase medicinalProductBase) {
        medicinalProductBase.setId(UUIDUtil.uuid());
        medicinalProductBase.settCreateTime(new Date());
        return medicinalProductBaseMapper.insert(medicinalProductBase);
    }

    @Override
    public int update(MedicinalProductBase medicinalProductBase) {
        /**
         * 先判断是否有图片更新
         */
        // 特征谱图
        String medicinalFeatureImgPaths = medicinalProductBase.gettMedicinalFeatureImgPath();
        if (medicinalFeatureImgPaths != null && !"".equals(medicinalFeatureImgPaths) && !medicinalFeatureImgPaths.equals(medicinalProductBase.gettMedicinalFeatureImgPathOut())) {
            String paths = Constant.IMG_PATH + medicinalProductBase.gettMedicinalFeatureImgPathOut();
            File files = new File(paths);
            if (files.exists()) {
                files.delete();
            }
        }

        //性状图片
        String medicinalSharpImgPaths=medicinalProductBase.gettMedicinalSharpImgPath();
        if(medicinalSharpImgPaths !=null && !"".equals(medicinalSharpImgPaths) && !medicinalSharpImgPaths.equals(medicinalProductBase.gettMedicinalSharpImgPathOut())){

            String paths = Constant.IMG_PATH  + medicinalProductBase.gettMedicinalSharpImgPathOut();
            File files = new File(paths);//文件图片
            if(files.exists()){
                files.delete();
            }
        }

        //鉴定图片
        String medicinalIdentifyImgPaths=medicinalProductBase.gettMedicinalIdentifyImgPath();
        if(medicinalIdentifyImgPaths !=null && !"".equals(medicinalIdentifyImgPaths) && !medicinalIdentifyImgPaths.equals(medicinalProductBase.gettMedicinalIdentifyImgPathOut())){

            String paths = Constant.IMG_PATH + medicinalProductBase.gettMedicinalIdentifyImgPathOut();
            File files = new File(paths);//文件图片
            if(files.exists()){
                files.delete();
            }
        }

        return medicinalProductBaseMapper.update(medicinalProductBase);
    }

    /**
     * 删除记录及相关图片
     * @param id   需要关联表中的联合主键id，还有删除的三个图片的路径
     * @return
     */
    @Override
    public int delete(String id) {

        MedicinalProductBase mp = medicinalProductBaseMapper.selectById(id);
        //若被删除的这个产地详情中的药材质量的性状图片存在，就删了
        if(mp.gettMedicinalSharpImgPath() != null && !mp.gettMedicinalSharpImgPath().equals("")) {
            deleteImgLocation((String)mp.gettMedicinalSharpImgPath());
        }

        //若被删除的这个产地详情中的药材质量的鉴定图片存在，就删了
        if(mp.gettMedicinalIdentifyImgPath() != null && !mp.gettMedicinalIdentifyImgPath().equals("")) {
            deleteImgLocation((String)mp.gettMedicinalIdentifyImgPath());
        }

        //若被删除的这个产地详情中的药材质量的特征图谱存在，就删了
        if(mp.gettMedicinalFeatureImgPath() != null && !mp.gettMedicinalFeatureImgPath().equals("")) {
            deleteImgLocation((String)mp.gettMedicinalFeatureImgPath());
        }

        return medicinalProductBaseMapper.delete(id);
    }

    /**
     * 保存图片的接口
     * @param file
     * @param request
     * @param map
     * @return
     */
    @Override
    public Map<String, Object> saveImg(MultipartFile file, HttpServletRequest request, Map<String, Object> map) {
        Map<String,Object> maps = new HashMap<String, Object>();

        try {
            // 判断是否拥有路径，没有就新建
            String path = Constant.IMG_PATH;
            if (!new File(path).exists()) {
                new File(path).mkdirs();
            }
            /** 将图片文件保存到服务器，同时返回变成后图片的名字 */
            String image = uploadImgFile(file, path, map);

            maps.put("code",true);
        } catch (Exception e) {
            maps.put("code",false);
            e.printStackTrace();
        }
        return maps;
    }

    private String uploadImgFile(MultipartFile file, String path, Map<String, Object> map) throws IOException {

        String name = file.getOriginalFilename();
        // lastIndexOf(".")：出现点的索引
        String suffixName = name.substring(name.lastIndexOf("."));

        String environmentdataUuid = (String)map.get("imgname");
        String fileName = environmentdataUuid+suffixName;

        File tempFile = new File(path,fileName);
        if(!tempFile.getParentFile().exists()){
            tempFile.getParentFile().mkdir();
        }
        if(tempFile.exists()){
            tempFile.delete();
        }
        tempFile.createNewFile();
        file.transferTo(tempFile);
        return tempFile.getName();
    }

    /**
     * 根据基地id删除
     * @param productBaseId
     * @return
     */
    @Override
    public int deleteProductBase(String productBaseId) {
        // TODO DELETE UPLOAD Pictures

        List<MedicinalProductBase> imgListOfTheProductBase = medicinalProductBaseMapper.selectImgOfProductBase(productBaseId);

        //删除相关图片
        for(MedicinalProductBase temp : imgListOfTheProductBase) {


            if(temp.gettMedicinalSharpImgPath() != null && !temp.gettMedicinalSharpImgPath().equals("")) {
                deleteImgLocation(temp.gettMedicinalSharpImgPath());
            }


            if(temp.gettMedicinalIdentifyImgPath() != null && !temp.gettMedicinalIdentifyImgPath().equals("")) {
                deleteImgLocation(temp.gettMedicinalIdentifyImgPath());
            }


            if(temp.gettMedicinalFeatureImgPath() != null && !temp.gettMedicinalFeatureImgPath().equals("")) {
                deleteImgLocation(temp.gettMedicinalFeatureImgPath());
            }


        }

        return medicinalProductBaseMapper.deleteProductBase(productBaseId);
    }

    /**
     * 根据药材id删除，代码基本跟上面相同
     * @param medicinalId
     * @return
     */
    @Override
    public int deleteMedicinal(String medicinalId) {
        List<MedicinalProductBase> imgListOfTheMedicinal = medicinalProductBaseMapper.selectImgOfMedicinal(medicinalId);


        //删除相关图片
        for(MedicinalProductBase temp : imgListOfTheMedicinal) {


            if(temp.gettMedicinalSharpImgPath() != null && !temp.gettMedicinalSharpImgPath().equals("")) {
                deleteImgLocation(temp.gettMedicinalSharpImgPath());
            }


            if(temp.gettMedicinalIdentifyImgPath() != null && !temp.gettMedicinalIdentifyImgPath().equals("")) {
                deleteImgLocation(temp.gettMedicinalIdentifyImgPath());
            }


            if(temp.gettMedicinalFeatureImgPath() != null && !temp.gettMedicinalFeatureImgPath().equals("")) {
                deleteImgLocation(temp.gettMedicinalFeatureImgPath());
            }


        }

        return medicinalProductBaseMapper.deleteMedicinal(medicinalId);  //删除表中相关记录并返回
    }

    /**
     * 删除图片
     * @param imgpath
     */
    public void deleteImgLocation(String imgpath){
        String path = Constant.IMG_PATH + imgpath;
        File file = new File(path);
        if (file.exists()){
            file.delete();
        }
    }
}
